package com.memory.modules.business.service.earn.impl;

import com.memory.common.data.PageSort;
import com.memory.modules.business.domain.earn.AccountEarnRecord;
import com.memory.modules.business.repository.earn.AccountEarnRecordRepository;
import com.memory.modules.business.service.earn.AccountEarnRecordService;
import com.memory.modules.business.service.earn.AccountEarnService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @PackageName: com.memory.modules.business.service.earn.impl
 * @ClassName: AccountEarnRecordServiceImpl
 * @Description:
 * @author: zhuguangxun
 * @date 2021/3/14
 */
@Service
@RequiredArgsConstructor
public class AccountEarnRecordServiceImpl implements AccountEarnRecordService {

    private final AccountEarnService accountEarnService;

    private final AccountEarnRecordRepository accountEarnRecordRepository;

    @Override
    public Page<AccountEarnRecord> findPage(Example<AccountEarnRecord> example) {
        final PageRequest pageRequest = PageSort.pageRequest();
        return accountEarnRecordRepository.findAll(example, pageRequest);
    }

    @Override
    @Transactional
    public AccountEarnRecord create(AccountEarnRecord record) {
        final AccountEarnRecord save = accountEarnRecordRepository.save(record);
        accountEarnService.saveAccountEarn(record.getAccountId(), record.getCount(), record.getCruEarn(), record.getCreateDate());
        return save;
    }

    @Override
    public void createAccountEarnRecord(Long accountId, Integer count, BigDecimal price, Date createDate) {
        AccountEarnRecord record = new AccountEarnRecord();
        record.setCount(count);
        record.setAccountId(accountId);
        record.setCruEarn(price);
        record.setCreateDate(createDate);
        Assert.notNull(accountEarnRecordRepository.save(record), "生成用户收益失败");
    }

    @Override
    public List<AccountEarnRecord> findByAccountId(Long accountId) {
        final List<AccountEarnRecord> earnRecords = accountEarnRecordRepository.findAccountEarnRecordByAccountId(accountId);
        return earnRecords;
    }
}
